--- 模块功能：remote脚本
-- @module remote
-- @author zpw
-- @license MIT
-- @copyright DEVELOPLINK
-- @release 2020.11.4
require "utils"
require "db"
require "http"
require "log"
module(..., package.seeall)


local path = (_G.is8955 and "/ldata/" or "/lua/")
local filePath = path.."remotedbg.cfg"
local remote = {}
remote.__index = remote
remote.remoteCfg = db.new(path .. "remote.cfg")
remote.filePath = filePath

-- 读取配置文件
function new()
    local o = remote.remoteCfg:export()
    log.info("remote.new", o.key,o.hash,o.path)
    return setmetatable(o, remote)
end

-- 加载本地文件
function remote:load(param)
    if  param and #param==2 and #param[2] > 10  then
        -- 测试文件是否存在
        local file = io.exists(self.filePath)
        if file==false then
            log.warn("remote.load：file not exist!")
            return
        else
            log.info("remote.load, start")
            log.info("remote.load, hash:", self.hash)
            log.info("remote.load, key:", self.key)
            log.info("remote.load, version:", self.version)
            -- 加载代码块到内存
            local p = self.filePath
            local back = "/" .. p:match("([^/]+)$") .. ".bak"
            local o = {path = io.exists(back) and back or p}
            log.info("remote.load, path:", o.path)
            if io.exists(o.path) then
                dofile(o.path)
            else
                log.warn("remote.load debug not exist!")
            end
        end
    else
        log.warn("remote load has been disabled!")
    end
end

local function httpDownloadCbFnc(result,statusCode,head,body)
    log.info("remote.httpDownloadCbFnc",result,statusCode,head)
    sys.publish("REMOTE_DOWNLOAD",result,statusCode,head)
end

--- 更新文件
-- @return nil
-- @usage db:serialize()
function remote:update(conf)
    log.info("remote update:", conf, #conf)
    if conf then
        local key = conf[1]
        local  hash = conf[2]
        log.info("remote conf:", key,hash, self.key, self.hash, self.path , self.remoteCfg)
        -- 查看是否更新了脚本
        if hash ~= self.hash then
            log.info("remote file should be update,path:", self.filePath)
            -- 需要更新脚本
            -- 删除文件
            log.info("remove old file!")
            local file = io.open(self.filePath, "w+")
            file:flush()
            file:close()
            -- 下载文件
            http.request("GET", key, nil, nil ,"", 20000, httpDownloadCbFnc, filePath)
            local sta,res,code = sys.waitUntil("REMOTE_DOWNLOAD", 10000)
            if sta and res and tonumber(code) == 200 then
                log.info("remote patch download success!")
                local c = misc.getClock()
                local remoteConf= {key = key, hash = hash, path = filePath, version = string.format("%04d%02d%02d-%02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)}
                log.info("remote patch key:", key, hash, filePath)
                self.key = key
                self.hash = hash
                self.path = filePath
                self.version = remoteConf.version
                -- 保存配置
                self.remoteCfg:import(remoteConf)
                log.info("remote patch save:",self.remoteCfg)
            else
                log.error("remote patch download failed!")
            end
        else
            log.info("remote patch is latest!")
        end
    end
end


